package com.atguigu.tingshu.search.listen;

import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/***
 * 监听上下架同步数据到ES中
 */
@Component
@Log4j2
public class AlbumInfoMessageLisener {
    @Autowired
    private ItemService itemService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 上架
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "albumIinfo_up_queue")
    public void AlbumInfoMessageLisenerUp(Channel channel, Message message){
        albumInfoMessageEs(channel, message, "1");
    }

    /**
     * 下架
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "albumIinfo_down_queue")
    public void AlbumInfoMessageLisenerDw(Channel channel, Message message){
        albumInfoMessageEs(channel, message, "0");
    }
    @SneakyThrows
    public void albumInfoMessageEs(Channel channel,Message message,String starts){
        //获取消息内容
        Long albumId = Long.valueOf(new String(message.getBody()));
        //获取消息属性
        MessageProperties properties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = properties.getDeliveryTag();
        try {
            if (starts.equals("1") ) {
                //上架
                itemService.albumInfoFromMysqlToEs(albumId);
            }else {
                //下架
                itemService.removeAlbumInfoFromMysqlToEs(albumId);
            }
        } catch (Exception e) {

            if(properties.getRedelivered()){
                //第二次失败
                redisTemplate.opsForSet().add("serach_up_or_down",albumId);
//                log.error("es专辑同步失败，专辑id为："+albumId+"失败原因："+e.getMessage());
                channel.basicReject(deliveryTag, false);
            }else {
                //再来一次
                channel.basicReject(deliveryTag, true);
            }
        }
    }
}
